package com.news.controller;


import com.news.model.auto.User;
import com.news.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 达瓦里氏
 * @since 2021-12-28
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private IUserService iUserService;

    /*查询用户*/
    @GetMapping("/getUser")
    public List<User> getUser(){
        return iUserService.list();
    }

    /*通过id查询用户*/
    @GetMapping("/getUserById/{id}")
    public User getUserById(@PathVariable("id") int id){
        return iUserService.getById(id);
    }

    /*修改用户*/
    @PostMapping("/updateUser")
    public void updateUser(@RequestBody User user){
        iUserService.updateById(user);
    }

    /*添加用户*/
    @PostMapping("/setUser")
    public void setUser(@RequestBody User user){
        iUserService.save(user);
    }

    /*删除用户*/
    @PostMapping("/deletedById/{id}")
    public boolean deleted(@PathVariable("id") int id){
        return iUserService.removeById(id);
    }

    /*前台用户登录*/
    @PostMapping("/login")
    public int Login(@RequestBody User user) {
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        User login = iUserService.login(user.getUsername(), user.getPassword());
        System.out.println(login.getId());
        if (login != null) {
            int id = login.getId();
            int a = Math.toIntExact(id);
            return a;
        } else {
            return -1;
        }
    }

    /*后台登录*/
    @PostMapping("/admin")
    public int selectAdmin(@RequestBody User user){
        System.out.println(user);
        int i = 0;
        String name = user.getUsername();
        System.out.println(name);
        try{
            i = iUserService.selectAdmin(name);
        }catch (Exception e){
            return -1;
        }
        if(i==1){
            User login = iUserService.login(user.getUsername(), user.getPassword());
            if (login != null) {
                int id = login.getId();
                int a = Math.toIntExact(id);
                return a;
            } else {
                return -1;
            }
        }else {
            return -1;
        }
    }
}
